<template>
  <div class="app-container">
    <div class="top" style="margin-top: 28px;">
      <el-input
        v-model="kwInput"
        placeholder="输入 网站编码 或 域名 进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" :disabled="listLoading" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button type="primary" class="el-icon-plus add-btn" @click="handleAction('create', '添加站点')">添加站点
      </el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="data" border fit highlight-current-row style="width: 100%">

      <!--<el-table-column align="center" width="100" prop="id" label="id" sortable></el-table-column>-->

      <el-table-column align="center" label="域名">
        <template slot-scope="scope">
          <el-input v-show="scope.row.edit" v-model="scope.row.domain" class="edit-input" size="small" />
          <span v-show="!scope.row.edit">{{ scope.row.domain }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="信息修改" width="260">
        <template slot-scope="scope">
          <el-input v-show="scope.row.edit" v-model="scope.row.code" placeholder="编码" class="edit-input" size="small" /><br>
          <el-input v-show="scope.row.edit" v-model="scope.row.m_frequency" placeholder="消息更新频率" class="edit-input" size="small" />
          <el-input v-show="scope.row.edit" v-model="scope.row.token" placeholder="token" class="edit-input" size="small" />
          <el-input v-show="scope.row.edit" v-model="scope.row.ds_username" placeholder="ds_user" class="edit-input" size="small" />
          <el-input v-show="scope.row.edit" v-model="scope.row.ds_password" placeholder="ds_password" class="edit-input" size="small" />
          <el-input v-show="scope.row.edit" v-model="scope.row.start_order_number" placeholder="起始单号" class="edit-input" size="small" />
          <span v-show="!scope.row.edit">{{ scope.row.code }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="类型">
        <template slot-scope="scope" class="mt-tag">
          <el-tag>{{ scope.row.type }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="目录同步信息" width="200">
        <template slot-scope="scope">
          <span><el-tag :type="scope.row.c_status | statusFilter">{{ scope.row.c_status }}</el-tag>
            {{ scope.row.c_sync_at | lineFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="属性同步信息" width="200">
        <template slot-scope="scope">
          <span><el-tag :type="scope.row.o_status | statusFilter">{{ scope.row.o_status }}</el-tag>
            {{ scope.row.o_sync_at | lineFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目属性" align="center" width="180">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.project_id"
            size="mini"
            placeholder="无"
            @change="handleProjectChange(scope.row)"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button
            v-if="scope.row.type==='supplier'"
            slot="reference"
            size="mini"
            type="success"
            plain
            style="margin-left:20px"
            :disabled="!scope.row.project_id"
            icon="el-icon-eye"
            @click="handleProjectAttrPreview(scope.row.project_id)"
          >查看
          </el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="500">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.edit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmEdit(scope.row)"
          >
            确认
          </el-button>
          <el-button
            v-show="scope.row.edit"
            class="cancel-btn"
            size="mini"
            icon="el-icon-refresh"
            type="warning"
            @click="cancelEdit(scope.row)"
          >取消
          </el-button>

          <el-button
            v-show="!scope.row.edit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="scope.row.edit=!scope.row.edit"
          >
            修改
          </el-button>
          <el-button
            v-show="!scope.row.edit"
            size="mini"
            icon="el-icon-delete"
            type="danger"
            plain
            @click="handleAction('delete', scope.row)"
          >删除
          </el-button>
          <el-dropdown
            split-button
            type="success"
            size="mini"
            @click="sync('catalog', scope.row.id)"
          >更新目录
            <el-dropdown-menu slot="dropdown" size="mini">
              <el-dropdown-item @click.native.stop="sync('product', scope.row.id)">更新产品属性</el-dropdown-item>
              <el-dropdown-item @click.native.stop="handleCrawlProduct(scope.row.id)">爬取产品</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!--<el-button v-show="!scope.row.edit" size="mini" icon="el-icon-refresh" type="success"-->
          <!--@click="sync('catalog', scope.row.id)" plain>更新目录-->
          <!--</el-button>-->
          <!--<el-button v-show="!scope.row.edit" size="mini" icon="el-icon-refresh" type="success"-->
          <!--@click="sync('product', scope.row.id)" plain>更新产品属性-->
          <!--</el-button>-->
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        v-if="action === 'create'"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="40px"
        style="margin-left: 8%"
      >
        <el-form-item label="域名" label-width="80px">
          <el-input v-model="temp.domain" />
        </el-form-item>

        <el-form-item label="网站编码" label-width="80px">
          <el-input v-model="temp.code" />
        </el-form-item>

        <el-form-item label="token" label-width="80px">
          <el-input v-model="temp.token" />
        </el-form-item>

        <el-form-item label="类型" label-width="80px">
          <el-input v-model="temp.type" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Post, Put, Delete, dt, Sync, ShowSyncStatus, AddCrawlWebProduct } from '@/api/erp/elicink/website'
import { Get as GetProjects } from '@/api/erp/elicink/project'

export default {
  name: 'SiteManage',
  filters: {
    lineFilter(v) {
      return v && ('|' + v)
    },
    statusFilter(v) {
      switch (v) {
        case '未同步':
          return 'info'
        case '同步中':
          return 'warning'
        case '已同步':
          return 'success'
        case '网络连接异常':
          return 'danger'
      }
    }
  },
  data() {
    return {
      data: [],
      listLoading: true,
      // 输入
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      dialogInputValue: '',
      dialogInputVsible: false,
      title: '',
      temp: {},

      projects: []
    }
  },
  created() {
    GetProjects()
      .then(response => {
        this.projects = response.data.data
      })
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        domain: '',
        code: '',
        type: 'PrestaShop',
        token: ''
      }
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      dt({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page
      })
        .then(response => {
          const items = response.data.data
          this.data = items.map(v => {
            this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
            v.originalDomain = v.domain //  will be used when user click the cancel botton
            v.originalType = v.type
            this.$set(v, 'inputValue', '')
            this.$set(v, 'inputVsible', false)
            return v
          })
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    cancelEdit(row) {
      row.domain = row.originalDomain
      row.type = row.originalType.concat() // 深拷贝
      row.edit = false
      row.inputVsible = false
      this.$message({
        message: '取消',
        type: 'warning'
      })
    },
    showInput(row) {
      row.inputVsible = true
    },
    confirmEdit(row) {
      Put(row.id, {
        domain: row.domain,
        code: row.code,
        type: row.type,
        m_frequency: row.m_frequency,
        ds_username: row.ds_username,
        ds_password: row.ds_password,
        start_order_number: row.start_order_number,
        token: row.token
      }).then(response => {
        row.edit = false
        row.inputVsible = false
        this.getList()
        this.notify('更新成功')
      })
    },
    handleCrawlProduct(id) {
      AddCrawlWebProduct(id).then(response => {
        this.notify('添加成功')
      })
    },
    handleClose(row, t) {
      row.type.splice(row.type.indexOf(t), 1)
    },
    handleInputConfirm(row) {
      const inputValue = row.inputValue
      if (inputValue && row.type.indexOf(inputValue) === -1) {
        row.type.push(inputValue)
      }
      row.inputValue = ''
      row.inputVsible = false
    },
    handleAction(action, row) {
      this.action = action
      this.dialogVisible = true
      switch (action) {
        case 'create':
          this.title = row
          this.resetTemp()
          break
        case 'delete':
          this.title = `确认要删除${row.domain}?`
          this.temp = row
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.dialogVisible = false
            this.dialogInputValue = ''
            this.dialogInputVsible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.dialogInputValue = ''
            this.dialogInputVsible = false
            this.getList()
            this.notify('删除成功')
          })
          return
      }
    },
    showDialogInput() {
      this.dialogInputVsible = true
    },
    handleDialogClose(t) {
      this.temp.type.splice(this.temp.type.indexOf(t), 1)
    },
    // handleDialogInputConfirm() {
    //   const inputValue = this.dialogInputValue;
    //   if (inputValue && this.temp.type.indexOf(inputValue) === -1) {
    //     this.temp.type.push(inputValue);
    //   }
    //   this.dialogInputValue = '';
    //   this.dialogInputVsible = false;
    // },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    sync(mode, id) {
      this.listLoading = true
      Sync(mode, id).then(response => {
        this.listLoading = false
        this.notify('同步中，请等待后台程序的执行.')
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    show_sync_status(id) {
      ShowSyncStatus(id)
        .then(response => {
          this.$alert(response.msg, '同步信息.', {
            confirmButtonText: '确定'
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleProjectChange(v) {
      this.listLoading = true
      Put(v.id,
        {
          project_id: v.project_id,
          only_project: 1
        })
        .then(response => {
          this.listLoading = false
          this.getList()
        }).catch(e => {
          this.listLoading = false
        })
    } // method end
  }
}
</script>

<style scoped>

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 130px
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> span.el-tag--info {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }
</style>
